package org.biloxi.game.gamerules.phaserules;

import org.biloxi.commands.Command;
import org.biloxi.commands.CommandRepository;
import org.biloxi.commands.Filter;
import org.biloxi.commands.Listener;
import org.biloxi.commands.changephase.ChangePhase;
import org.biloxi.commands.changephase.ChangePhase.Options;
import org.biloxi.commands.changephase.ChangePhase.Result;
import org.biloxi.game.gamerules.GameRule;
import org.biloxi.model.GameState;
import org.biloxi.model.GameState.Phase;
import org.biloxi.player.actions.ActionOptionPair;

public class PhaseRule extends GameRule implements Listener<ChangePhase.Options, ChangePhase.Result> {
		
	public PhaseRule(CommandRepository cmd) {
		super(cmd);

		// Attach Listeners
		_c.changePhase().do_(
			this,
			new Filter<Result>(){ public boolean allow(Result result) {
				return ( !result.phase.toString().contains("After") &&
						  result.phase != Phase.BOT &&
						  result.phase != Phase.EOT );
			}}
		);
	}

	public void handle(Command<Options, Result> cmd, Options options, Result result, GameState g) {
		
		if(!g.getTurnsPlayerState().hasLost()){
			ActionOptionPair<?>[] actions = _c.requestPlayerActions(g.getTurnsPlayerID());
			if(actions != null){
				for(ActionOptionPair<?> ao : actions){
					if(ao.isLegal(g, g.getTurnsPlayerState()))
						ao.execute(g, g.getTurnsPlayerState(),_c);
				}
			}
						
			_c.changePhase( new ChangePhase.Options(Phase.getNextPhase(result.phase)) );
		}
	}

}
